package com.wangyf.thread2;

import java.util.concurrent.CountDownLatch;

/**
 * 测试指令重排序
 * 正常情况下 永远不可能出现 打印
 * @author wangyf
 * @date 2021/7/21 20:01
 * 原因就是jvm在执行的时候有可能优化执行，进行指令重排序
 */
public class T10_DisOrder {
    public static int x = 0, y = 0;
    public static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            x = 0;
            y = 0;
            a = 0;
            b = 0;

            CountDownLatch latch = new CountDownLatch(2);

            Thread t1 = new Thread(() -> {
                a = 1;
                x = b;

                latch.countDown();
            });
            Thread t2 = new Thread(() -> {
                b = 1;
                y = a;

                latch.countDown();
            });

            t1.start();
            t2.start();

            latch.await();

            if (x == 0 && y == 0) {
                System.out.println("第"+i+ "次(" + x +", " + y +" )");
            }
        }
    }
}
